<template>
  <el-dialog :close-on-click-modal='false' v-drag :title="record.id?$t('编辑') : $t('添加')" :v-="dialogVisible" :visible.sync="dialogVisible" width="900px" top="10px" @close='close'>
    <div class="dialogContentBoxMaxHeight100">
      <el-form ref="form" :model="record" label-width="100px" :rules="rules" class="ipsForm" label-position="left" style="margin:0 30px;">
        <el-form-item :label="$t('策略名称')" prop="name">
          <el-input v-emoji v-model="record.name" ref="name" style="width:370px;" size='small'></el-input>
        </el-form-item>
        <el-form-item :label="$t('规则集类型')" prop="ruleType">
          <el-select v-model="ruleType" ref="ruleTyped" size='small' filterable clearable @change="ruleTypeChange" style="width:370px;">
            <el-option v-for="item in ruleTypeList" :key="item.class_type" :label="$t(lpsNameList[item.class_type])" :value="item.class_type">
            </el-option>
          </el-select>
        </el-form-item>
        <div class="strategyFatherBox">
          <el-button type="success" size='small' @click="largeConfig" class="largeConfig">{{$t('批量配置')}}</el-button>
        </div>
        <div style="margin-top:20px">
          <el-table ref="multipleTable" size='mini' v-if="multipleTableShow" height='500px' v-loading='loading' :data="ruleList" :row-key="getRowName" @selection-change="autoDetectChange">
            <el-table-column type="selection" :reserve-selection="true" align='center' width="55"></el-table-column>
            <el-table-column prop="class_type" align='center' :label="$t('规则集类型')" min-width="200">
              <template slot-scope="scope">
                {{ $t(lpsNameList[scope.row.class_type]) }}
              </template>
            </el-table-column>
            <el-table-column prop="class_name" align='center' :label="$t('规则集名称')" min-width="200">
              <template slot-scope="scope">
                {{ $t(lpsNameList[scope.row.class_name]) }}
              </template>
            </el-table-column>
            <el-table-column prop="action" align="center" :label="$t('动作')" width="200">
              <template slot-scope="scope">
                <el-select v-model="scope.row.action" style="width:150px;" :ref="'property' + (scope.$index + 1)" :disabled='scope.row.class_name === "industry-scada"' size='mini' @change='updateTable(scope.row)'>
                  <el-option v-for="item in typeList" :key="item.value" :label="$t(item.label)" :value="item.value">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column align='center' width='120' :label="$t('操作')">
              <template slot-scope="scope">
                <el-button type="success" plain size="mini" @click="ruleInfoClick(scope.row)" :class="'ruleInfo' + (scope.$index + 1)">{{$t('详细信息')}}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
    </div>
    <ips-batch-dialog v-if="ipsBatchDialogVisible" ref="refIpsBatchDialogVisible" @showSeclectRow='showSeclectRow'></ips-batch-dialog>
    <ruleInfoDialog v-if="ruleInfoDialogVisible" ref="refRuleInfoDialogVisible"></ruleInfoDialog>
    <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit" class="addSubmit">{{$t('确 定')}}</el-button>
      <el-button @click="close" class="addClose">{{$t('取 消')}}</el-button>
    </span>
  </el-dialog>
</template>
<script>
import { getRuleType, getRuleArray, addIps, editIps } from '@/api/safe/ips'
import ipsList from '../ipsArray'
import ruleInfoDialog from './ruleInfoDialog.vue'
import IpsBatchDialog from './IpsBatchDialog.vue'
import { inputClass, selectClass } from '@/utils/input-class.js'
export default {
  components: { ruleInfoDialog, IpsBatchDialog },
  name: 'IpsDialog',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入策略名称')))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      ipsBatchDialogVisible: false,
      ruleInfoDialogVisible: false,
      record: {
        id: null,
        name: '',
        rule: ''
      },
      recordCopy: {
        id: null,
        name: '',
        rule: ''
      },
      name: '',
      multipleTableShow: true,
      ruleType: null,
      lpsNameList: ipsList,
      ruleTypeList: [],
      ruleList: [],
      ruleAllList: [],
      ruleDataList: [],
      loading: false,
      typeList: [ //   alert/block  告警/阻断
        { value: 'alert', label: '告警' },
        { value: 'block', label: '阻断' }
      ],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }]
      }
    }
  },
  methods: {
    async init (data) {
      this.dialogVisible = true
      this.$nextTick(() => {
        const data = ['name']
        const selectData = ['ruleTyped']
        inputClass(this.$refs, data)
        selectClass(this.$refs, selectData)
      })
      this.loading = true

      await getRuleType().then(res => {
        if (res.status === 0) {
          this.ruleTypeList = res.info
        }
      })
      await getRuleArray().then(res => {
        if (res.status === 0) {
          this.ruleList = res.info[0].class_map
          this.ruleAllList = res.info[0].class_map
          this.ruleAllList = this.ruleList
          this.loading = false
          if (data) {
            this.record.name = data.name
            this.name = data.name
            this.record.id = data.id
            data.class_map.forEach((row, index) => {
              this.ruleList.forEach((item, index) => {
                if (row.class_name === item.class_name) {
                  this.$refs.multipleTable.toggleRowSelection(item, true)
                  this.ruleList[index].action = row.action
                }
              })
            })
          }
          this.$nextTick(() => {
            this.ruleList.forEach((item, ind) => {
              if (!item.action) {
                item.action = 'alert'
              }
              const selectData = ['property' + (ind + 1)]
              selectClass(this.$refs, selectData)
            })
          })
        }
      })
    },
    getRowName (row) {
      return row.class_name
    },
    autoDetectChange (data) {
      this.ruleDataList = data
    },
    ruleTypeChange (type) {
      this.ruleList = []
      if (type) {
        for (let item of this.ruleAllList) {
          if (item.class_type === type) {
            this.ruleList.push(item)
          }
        }
      } else {
        this.ruleList = this.ruleAllList
        this.$nextTick(() => {
          this.ruleList.forEach((item, ind) => {
            const selectData = ['property' + (ind + 1)]
            selectClass(this.$refs, selectData)
          })
        })
      }
      this.showSeclectRowEdit(this.ruleDataList)
    },
    showSeclectRowEdit (data) {
      if (data.length > 0) {
        data.forEach(row => {
          this.ruleList.forEach((item, index) => {
            if (row.class_name === item.class_name) {
              this.$refs.multipleTable.toggleRowSelection(item, true)
              this.ruleList[index].action = row.action
            }
          })
        })
      }
    },
    showSeclectRow (data) {
      this.ipsBatchDialogVisible = false
      if (data.length > 0) {
        data.forEach(row => {
          this.ruleList.forEach((item, index) => {
            if (row.class_name === item.class_name) {
              this.ruleList[index].action = row.action
              this.$refs.multipleTable.toggleRowSelection(item)
              this.$refs.multipleTable.toggleRowSelection(item, true)
            }
          })
        })
      }
      this.multipleTableShow = false
      this.multipleTableShow = true
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.ruleDataList.length > 0) {
            var formData = JSON.parse(JSON.stringify(this.record))
            formData.rule = ''
            for (let item of this.ruleDataList) {
              formData.rule += ',' + item.class_name + ':' + item.action
            }
            formData.rule = formData.rule.substr(1, formData.rule.length - 1)
            if (this.name === formData.name) {
              formData.name = null
            }
            if (formData.id) {
              editIps(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('编辑成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$emit('listData')
                }
              })
            } else {
              addIps(formData).then(res => {
                if (res.status === 0) {
                  this.$message({
                    message: this.$t('添加成功'),
                    type: 'success'
                  })
                  this.close()
                  this.$emit('listData')
                }
              })
            }
          } else {
            this.$message({
              message: this.$t('请至少选择一条数据进行添加'),
              type: 'error'
            })
          }
        }
      })
    },
    // 批量配置按钮
    largeConfig (data) {
      this.ipsBatchDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refIpsBatchDialogVisible.init(data)
      })
    },
    close () {
      this.dialogVisible = false
      this.ruleType = null
      this.ruleTypeList = []
      this.ruleList = []
      this.ruleAllList = []
      this.ruleDataList = []
      this.name = ''
      this.loading = false
      this.record = Object.assign({}, this.recordCopy)
      this.$refs.multipleTable.clearSelection()
      this.$refs.form.resetFields()
    },
    updateTable (data) {
      var updata = this.ruleList
      this.ruleList = []
      for (let item of updata) {
        this.ruleList.push(item)
      }
    },
    ruleInfoClick (data) {
      this.ruleInfoDialogVisible = true
      this.$nextTick(() => {
        this.$refs.refRuleInfoDialogVisible.init(data.class_name)
      })
    }
  }
}
</script>
